package com.lianxueda.drawing.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lianxueda.drawing.domain.pojo.WxUser;
import com.lianxueda.drawing.mapper.WxUserMapper;
import com.lianxueda.drawing.service.WxUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 29264
 */
@Service
public class WxUserServiceImpl
        extends ServiceImpl<WxUserMapper, WxUser>
        implements WxUserService {

    @Resource
    private WxUserMapper userMapper;



    @Resource
    private WxUserMapper wxUserMapper;


    @Override
    public boolean userExists(String openId) {
        return wxUserMapper.existsByOpenId(openId);
    }

    @Override
    public void updateUser(WxUser wxUser) {
        // 查找用户记录
        WxUser existingUser = wxUserMapper.findByOpenId(wxUser.getOpenid());

        if (existingUser != null) {
            // 更新用户信息
            existingUser.setNickname(wxUser.getNickname());
            existingUser.setAvatar(wxUser.getAvatar());

            // 执行更新操作
            wxUserMapper.updateById(existingUser);
        }
    }
    @Override
    public void addUser(WxUser wxUser) {
        WxUser user = new WxUser();
        //复制
        user.setOpenid(wxUser.getOpenid());
        user.setNickname(wxUser.getNickname());
        user.setAvatar(wxUser.getAvatar());
        user.setPhoneNumber(wxUser.getPhoneNumber());
        user.setName("dd");
        user.setRelation("dd");
        wxUserMapper.insert(user);
    }

    @Override
    public WxUser findByOpenId(String openid) {
        return wxUserMapper.findByOpenId(openid);
    }

    @Override
    public boolean updatePhoneAndRelationStudentId(String openId, String phone, Integer studentId, String relation,String name) {
        // 查找用户
        WxUser user = userMapper.findByOpenId(openId);

        if (user == null) {
            // 如果用户不存在，返回 false
            return false;
        }

        // 更新用户信息
        user.setPhoneNumber(phone);
        user.setStudentId(studentId);
        user.setRelation(relation);
        user.setName(name);

        // 保存更新
        int rowsAffected = userMapper.updateById(user);

        // 返回操作是否成功
        return rowsAffected > 0;
    }


    @Override
    public List<Map<Integer, String>> getOpenIdByStudentIds(List<Integer> studentId) {
        List<Map<String, Object>> resultList = wxUserMapper.getOpenIdByStudentIds(studentId);
        return resultList.stream().map(row -> {
            Map<Integer, String> map = new HashMap<>();
            map.put((Integer) row.get("studentId"), (String) row.get("openId"));
            return map;
        }).collect(Collectors.toList());
    }

}
